<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdated ? t('common.edit') : t('common.create')"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :minHeight="450"
    :width="1200"
  >
    <Tabs v-model:activeKey="detailActiveKey">
      <TabPane key="1" :tab="t('routes.demo.documentManager.property')">
        <BasicForm @register="registerForm" :schemas="schemasData" />
      </TabPane>
      <TabPane key="2" :tab="t('routes.demo.documentManager.attachment')" :forceRender="true">
        <BasicUpload
          :maxSize="20"
          :maxNumber="10"
          @preview-delete="handlePreviewDelete"
          :api="uploadFileApi"
          v-model:value="fileList"
          :showOkBtn="!AttOrAssDisabled"
          @change="handleUploadOk"
        />
      </TabPane>
      <TabPane key="3" :tab="t('routes.demo.documentManager.associated')" :forceRender="true">
        <BasicTable @register="registerAssociation" :dataSource="fileAssociationList">
          <template #toolbar>
            <a-button type="primary" @click="handleAssociated" :disabled="AttOrAssDisabled">
              {{ t('routes.demo.documentManager.associatedObject') }}
            </a-button>
          </template>
        </BasicTable>
      </TabPane>
      <TabPane
        key="4"
        :tab="t('routes.demo.documentManager.reverseAssociated')"
        :forceRender="true"
      >
        <BasicTable @register="registerBeAssociation" :dataSource="associationFileList" />
      </TabPane>
    </Tabs>
    <!-- 关联，反关联弹窗 -->
    <assObjModal @register="registerAssociatedModal" @success="updateAssociationTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicUpload } from '/@/components/Upload';
  import { useUserStore } from '/@/store/modules/user';

  import assObjModal from './assObjModal.vue';

  import { uploadFileApi } from '/@/api/sys/upload';

  import {
    getBaseDetail,
    createPictureDoc,
    GetPdmDocAttributeData,
    getPrdFileDetail,
    UpdateFileDetails,
  } from '/@/api/demo/document';

  import { getAssociation, getBeAssociation } from './tableData';

  const emit = defineEmits(['register', 'success']);
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const detailActiveKey = ref<string>('1');
  const fileAssociationList = ref<any>([]);
  const associationFileList = ref<any>([]);
  const haveThitObjectId = ref<string>('');
  const folderId = ref<string>('');
  const isUpdated = ref<boolean>(false);
  const schemasData = ref<any>([]);
  const currentRecord = ref<any>({});
  const fileList = ref<any>([]);
  const docIsUpdated = ref<boolean>(false); // 判断文档是否修改
  const AttOrAssDisabled = ref<boolean>(false); // 判断附件和关联是否禁用
  const SelectedOid = ref<string>(''); // 选中附件的oid
  const selectedDoctype = ref<string>(''); // 选中附件的文件类型
  const newData = ref<any>({});
  const docType = ref<string>('');
  const useCommonStore = useUserStore();
  const reorganizeJson = (input) => {
    // 获取固定属性
    const {
      creater,
      createtime,
      filename,
      filetype,
      name,
      oid,
      securitylevel,
      status,
      ThitObjectId,
      version,
      ...expandObj
    } = input;

    // 返回重组后的对象
    return {
      creater,
      createtime,
      filename,
      filetype,
      name,
      oid,
      securitylevel,
      status,
      thitObjectId: ThitObjectId,
      version,
      expandObj,
    };
  };
  //上传成功
  const handleUploadOk = (fileList) => {
    const fileName = fileList[0].split('/').pop(); // 获取文件名
    if (!isUpdated.value) {
      setPropFields({ filename: fileName });
    }
  };

  // 提交
  async function handleSubmit() {
    const values = await validField();
    // 状态映射表
    const statusMap = {
      生效: '8',
      废止: '16',
      检出: '1',
    };
    // 修改 status
    values.status = statusMap[values.status] ?? values.status; // 如果找不到对应值，则保留原值
    setModalProps({ confirmLoading: true });
    if (unref(isUpdated)) {
      // 修改
      if (currentRecord.value.state != '1') {
        createMessage.error('非检出状态不允许修改');
        setModalProps({ confirmLoading: false });
      } else {
        const params = {
          fileQuality: reorganizeJson(values),
          fileAttachments: fileList.value,
          fileAssociationList: fileAssociationList.value,
          associationFileList: associationFileList.value,
          resultIsNotSame: docIsUpdated.value,
        };
        await UpdateFileDetails(params);
        createMessage.success(t('common.updateSuccessText'));
        emit('success');
        handleCancel();
      }
    } else {
      // 新增
      const params = {
        haveThitObjectId: haveThitObjectId.value,
        folderId: folderId.value,
        fileQuality: reorganizeJson(values),
        fileAssociationList: fileAssociationList.value,
        fileUrls: fileList.value,
        docType: docType.value,
      };
      await createPictureDoc(params);
      createMessage.success(t('common.addSuccessText'));
      emit('success');
      handleCancel();
    }
  }

  // 取消
  const handleCancel = () => {
    detailActiveKey.value = '1';
    fileAssociationList.value = [];
    associationFileList.value = [];
    haveThitObjectId.value = '';
    folderId.value = '';
    fileList.value = [];
    closeModal();
  };

  const handlePreviewDelete = () => {
    if (isUpdated.value) {
      docIsUpdated.value = true;
    }
  };

  //关联对象
  const handleAssociated = () => {
    openAssociatedModal(true, {
      isAssociation: true,
      selectedDirKey: folderId.value,
      SelectedOid: SelectedOid.value,
      selectedDoctype: selectedDoctype.value,
      isFrom: '图档详情',
    });
  };

  //更新关联表格
  const updateAssociationTable = (params) => {
    const newParams = {
      thitObjectId: params.name,
      version: params.version,
      name: params.filename,
      doctype: params.doctype,
      creater: params.creator,
    };
    fileAssociationList.value = [...fileAssociationList.value, newParams];
  };

  // attr过滤控件方法
  const filterOption = (type) => {
    // 文本框
    const textArr = ['4101', '256', '21', '17', '264'];
    // 下拉框
    const selectArr = ['145', '128', '136', '384', '392', '640'];
    // 选用日历
    const dateArr = ['8448', '8456'];
    // 资源控件
    const resourceArr = ['1024', '1032', '1280', '1288'];
    // 资源控件多选
    const resourceMultiArr = ['768', '776'];
    // 选择框
    const checkboxArr = ['16384', '16392'];
    // 网格
    const gridArr = ['512', '520'];
    // 下拉选择数据源
    const selectDataSourceArr = ['131072', '131080'];
    // 关联文件
    const relatedFileArr = ['262144', '262152'];
    // 下拉多选
    const selectMultiArr = ['32768', '32776'];
    if (textArr.includes(type)) {
      return 'Input';
    } else if (selectArr.includes(type)) {
      return 'Select';
    } else if (dateArr.includes(type)) {
      return 'DatePicker';
    } else if (resourceArr.includes(type)) {
      return 'Upload';
    } else if (resourceMultiArr.includes(type)) {
      return 'Upload';
    } else if (checkboxArr.includes(type)) {
      return 'Select';
    } else if (gridArr.includes(type)) {
      return 'Input';
    } else if (selectDataSourceArr.includes(type)) {
      return 'Select';
    } else if (relatedFileArr.includes(type)) {
      return 'Input';
    } else if (selectMultiArr.includes(type)) {
      return 'Select';
    } else {
      return '';
    }
  };

  const getSelectOptions = (options) => {
    if (!options) return []; // 如果 options 为空，返回空数组
    return options.split(',').map((item) => ({
      label: item.trim(), // 去除可能的空格
      value: item.trim(),
    }));
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    resetPropFields();
    // fileType图档类型、selectedDirKey目录ID、isUpdate是否新建、record 当前数据
    const { fileType, selectedDirKey, isUpdate, record } = data;
    docType.value = fileType;
    isUpdated.value = isUpdate;
    folderId.value = selectedDirKey;
    currentRecord.value = record;
    const newRes = await getBaseDetail(fileType);
    haveThitObjectId.value = newRes.haveThitObjectId; // 1有默认的代号设置0没有
    newData.value = newRes.fileQuality;
    // 组织属性格式
    function getStatusLabel(defaultValue) {
      const statusMap = {
        '1': '检出',
        '8': '生效',
        '16': '废止',
      };
      return statusMap[defaultValue] || '未知状态';
    }

    /**
     * 判断字段是否禁用
     * @param {string} prop 字段名
     * @param {boolean} isUpdate 是否为修改模式
     * @param {Set} createSet 新增时禁用字段集合
     * @param {Set} updateSet 修改时禁用字段集合
     * @param {string} checkOutPerson 检出人
     * @param {number} state 状态
     * @param {string} currentUser 当前登录人
     * @returns {boolean} 是否禁用
     */
    function isFieldDisabled(
      prop,
      isUpdate,
      createSet,
      updateSet,
      checkOutPerson,
      state,
      currentUser,
    ) {
      if (!isUpdate) {
        // 新增模式，判断是否在 createSet 中
        return createSet.has(prop);
      }

      // 修改模式下，首先判断当前登录人是否是 checkOutPerson
      if (currentUser !== checkOutPerson) {
        return true; // 当前用户不是 checkOutPerson，字段禁用
      }

      // 当前用户是 checkOutPerson，进一步判断状态
      if (state === '8') {
        return true; // 状态为 8，字段禁用
      }

      if (state === '1') {
        return updateSet.has(prop); // 状态为 1，判断字段是否在 updateSet 中
      }

      return false; // 其他情况，字段不禁用
    }

    // 判断附件关联是否禁用
    function isAttOrAssDisabled(isUpdate, checkOutPerson, state, currentUser) {
      if (!isUpdate) {
        return false;
      }

      // 修改模式下，首先判断当前登录人是否是 checkOutPerson
      if (currentUser !== checkOutPerson) {
        return true; // 当前用户不是 checkOutPerson，字段禁用
      }

      // 当前用户是 checkOutPerson，进一步判断状态
      if (state === '8') {
        return true; // 状态为 8，字段禁用
      }

      if (state === '1') {
        return false; // 状态为 1，字段启用
      }

      return false;
    }

    GetPdmDocAttributeData(fileType).then((res) => {
      const disabledFieldsForCreate = new Set([
        'creater',
        'createtime',
        'oid',
        'status',
        'version',
      ]);

      const disabledFieldsForUpdate = new Set([
        'creater',
        'createtime',
        'filename',
        'oid',
        'securitylevel',
        'status',
        'ThitObjectId',
        'version',
      ]);

      AttOrAssDisabled.value = isAttOrAssDisabled(
        isUpdate,
        isUpdate ? record.checkOutPerson : '',
        isUpdate ? record.state : '',
        useCommonStore.userInfo.userId,
      );
      schemasData.value = res.listDocData.map(({ prop, attr, name, defaultValue, pdmnull }) => {
        const isDisabled = isFieldDisabled(
          prop,
          isUpdate,
          disabledFieldsForCreate,
          disabledFieldsForUpdate,
          isUpdate ? record.checkOutPerson : '',
          isUpdate ? record.state : '',
          useCommonStore.userInfo.userId,
        );

        return {
          field: prop,
          component: filterOption(attr),
          label: name,
          componentProps: {
            placeholder: `请输入${name}`,
            disabled: isDisabled,
            options: filterOption(attr) == 'Select' ? getSelectOptions(defaultValue) : undefined,
          },
          defaultValue:
            prop === 'status'
              ? getStatusLabel(defaultValue)
              : filterOption(attr) == 'Select'
              ? []
              : defaultValue,
          required: pdmnull == 0,
        };
      });
      if (haveThitObjectId.value === '1') {
        setPropFields({ ThitObjectId: newData.value.thitObjectId });
      }
      // 获取prop为oid的对象
      const oidObject = res.listDocData.find((item) => item.prop === 'oid');
      // 获取defaultValue
      const OidValue = oidObject ? oidObject.defaultValue : '';
      SelectedOid.value = OidValue;
      // 获取prop为filetype的对象
      const fileTypeObject = res.listDocData.find((item) => item.prop === 'filetype');
      // 获取defaultValue
      const FileTypeValue = fileTypeObject ? fileTypeObject.defaultValue : '';
      selectedDoctype.value = FileTypeValue;
    });
    if (isUpdate) {
      // 编辑
      getPrdFileDetail(record.oId).then((res) => {
        // 设置属性
        const newData = { ...res.fileQuality, ...res.fileQuality.expandObj };
        if (newData.hasOwnProperty('thitObjectId')) {
          newData['ThitObjectId'] = newData['thitObjectId'];
          delete newData['thitObjectId'];
        }
        delete res.fileQuality.expandObj;
        setPropFields(newData);
        // 设置附件
        fileList.value = res.fileAttachments[0].fileUrl;
        // 设置关联图档
        fileAssociationList.value = res.fileAssociationList;
        // 设置被关联图档
        associationFileList.value = res.associationFileList;
        SelectedOid.value = res.fileQuality.oid;
        selectedDoctype.value = res.fileQuality.filetype;
      });
    }
  });

  // 属性详情
  const [
    registerForm,
    { setFieldsValue: setPropFields, validate: validField, resetFields: resetPropFields },
  ] = useForm({
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
    showResetButton: false,
    showSubmitButton: false,
  });
  // 关联详情
  const [registerAssociation] = useTable({
    titleHelpMessage: 'createDocAss',
    columns: getAssociation(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
  });
  // 被关联详情
  const [registerBeAssociation] = useTable({
    titleHelpMessage: 'createDocBeAss',
    columns: getBeAssociation(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
  });

  // 关联，反关联弹窗
  const [registerAssociatedModal, { openModal: openAssociatedModal }] = useModal();
</script>
